<!--
* @author wn
* @date 2023/03/10 17:20:13
* @description: 工艺流程 页面
!-->
<template>
	<a-card :bordered="false" style="margin: 12px">
		<!-- 查询区域 -->
		<div class="table-page-search-wrapper">
			<!-- 搜索区域  回车触发聚焦 @keyup.enter.native -->
			<a-form layout="inline">
				<a-row :gutter="24">
					<a-col :md="6" :sm="8">
						<a-form-item
							label="工艺流程编码"
							:labelCol="{ span: 12 }"
							:wrapperCol="{ span: 14, offset: 1 }"
						>
							<a-input
								placeholder="请输入工艺流程编码"
								v-model.trim="queryParam.ord_no"
							></a-input>
						</a-form-item>
					</a-col>
					<!--  -->
					<template v-if="toggleSearchStatus">
						<a-col :md="6" :sm="8">
							<a-form-item
								label="工艺流程版本"
								:labelCol="{ span: 12 }"
								:wrapperCol="{ span: 14, offset: 1 }"
							>
								<a-input
									placeholder="请输入工艺流程版本"
									v-model.trim="queryParam.c01"
								></a-input>
							</a-form-item>
						</a-col>
						<a-col :md="6" :sm="8">
							<a-form-item
								label="到期日期"
								:labelCol="{ span: 12 }"
								:wrapperCol="{ span: 16, offset: 1 }"
							>
								<a-input
									placeholder="请输入到期日期"
									v-model.trim="queryParam.due_date"
								></a-input>
							</a-form-item>
						</a-col>
					</template>
					<!--  -->
					<a-col :md="10" :sm="12">
						<a-form-item
							label="创建时间(起止)"
							:labelCol="{ span: 12 }"
							:wrapperCol="{ span: 19, offset: 1 }"
						>
							<a-range-picker
								v-model.trim="queryParam.createTime"
								:showTime="true"
								date-format="YYYY-MM-DD HH:mm:ss"
							></a-range-picker>
						</a-form-item>
					</a-col>
					<a-col :md="8" :sm="24" class="table-page-search-submitButtons">
						<a-button type="primary" @click="searchOrderQuery">
							<template #icon><Icon :icon="iSearch" /></template>
							查询
						</a-button>
						<a-button style="margin-left: 8px" @click="searchReset">
							<template #icon><Icon :icon="iReload" /></template>
							重置
						</a-button>

						<a
							@click="toggleSearchStatus = !toggleSearchStatus"
							style="margin-left: 8px"
						>
							{{ toggleSearchStatus ? '收起' : '展开' }}
							<Icon :icon="toggleSearchStatus ? iUp : iDown" />
						</a>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<!-- table区域-begin -->
		<section>
			<!-- 头部 -->
			<div class="table-operator ant-alert ant-alert-info">
				<div>
					<a-divider type="vertical" />
					<a @click="handleAdd"><Icon :icon="iPlus" />新增</a>
					<a-divider type="vertical" />
					<a
						@click="handleModify"
						:class="{ disabled: !selectedRowKeys.length || loading }"
					>
						<Icon :icon="iEdit" />
						编辑
					</a>
					<a-divider type="vertical" />
					<a
						@click="handleProcessFlowCopy"
						:class="{ disabled: !selectedRowKeys.length || loading }"
					>
						<Icon :icon="iEdit" />复制
					</a>
					<a-divider type="vertical" />
					<a
						@click="handleRecordDelete('PROCESS_FLOW', true)"
						:class="{ disabled: !selectedRowKeys.length || loading }"
					>
						<Icon :icon="iDelete" />删除
					</a>
					<a-divider type="vertical" />
				</div>
				<!-- Popover 气泡卡片 -->
				<span class="float-right">
					<a-popover title="自定义列" trigger="click" placement="leftBottom">
						<template #content>
							<!-- :defaultValue="settingColumns"
								v-model:value.trim="settingColumns"
							-->
							<a-checkbox-group @change="onColSettingsChange">
								<a-row style="width: 400px">
									<template v-for="item in defColumns" :key="item.title">
										<a-col
											:span="12"
											v-if="
												item.key !== 'rowIndex' && item.dataIndex !== 'action'
											"
										>
											<a-checkbox :value="item.dataIndex">
												<ellipsis :value="item.title" />
											</a-checkbox>
										</a-col>
									</template>
								</a-row>
							</a-checkbox-group>
						</template>
						<a><Icon :icon="iSetting" />设置</a>
					</a-popover>
				</span>
			</div>

			<!-- table
			rowKey="ord_id"  表格行 key 的取值，可以是字符串或一个函数
			-->
			<a-table
				ref="table"
				size="middle"
				bordered
				rowKey="ord_id"
				:columns="columns"
				:dataSource="dataSource"
				:pagination="pagination"
				:loading="loading"
				:scroll="{ x: scrollX, y: scrollY }"
				:rowSelection="{
					type: 'radio',
					selectedRowKeys: selectedRowKeys,
					onChange: onSelectChange,
					getCheckboxProps: getCheckboxProps,
				}"
				@change="handleTableChange"
				:customRow="customRow"
			>
				<!-- 固定头和列 -->
				<template #bodyCell="{ index, record, column }">
					<template v-if="column.dataIndex === 'action'">
						<span>
							<a @click="handleEdit(record)">编辑</a>
							<a-divider type="vertical" />
							<a-dropdown>
								<a class="ant-dropdown-link">
									更多
									<Icon :icon="DownOutlined" />
								</a>
								<template #overlay>
									<a-menu>
										<a-menu-item>
											<a href="javascript:;" @click="handleDetail(record)">
												详情
											</a>
										</a-menu-item>

										<a-menu-item>
											<a-popconfirm
												title="确定删除吗?"
												@confirm="
													() =>
														handleDelete('Process_Flow', true, record.ord_id)
												"
											>
												<a>删除</a>
											</a-popconfirm>
										</a-menu-item>
									</a-menu>
								</template>
							</a-dropdown>
						</span>
					</template>
					<!-- # 索引 + 1 -->
					<template v-else-if="column.title === '#'"> {{ index + 1 }}</template>
					<!-- 字符串超长截取省略号显示, 在tooltip里面显示全部信息 -->
					<template v-else>
						<ellipsis :value="record[column.dataIndex] || ''" />
					</template>
				</template>
			</a-table>
		</section>
		<!-- table区域-end -->

		<!-- 表二 暴露 加载数据的方法 父表 选中时调用-->
		<a-tabs :activeKey="1" @change="onTabClick">
			<a-tab-pane tab="工序明细" :key="1" :forceRender="true">
				<ProcessFlowSUBList ref="target" />
			</a-tab-pane>
		</a-tabs>

		<!-- 弹框 -->
		<process-flow-modal ref="flowModal" />
	</a-card>
</template>
<script setup>
// npm install moment
import Moment from 'moment'
import { Icon } from '@/antd/icons'
import { computed, reactive, ref } from 'vue'
import Ellipsis from '@/components/tools/Ellipsis'
import { loadOrderData } from '@/api/table'
// npm install vue-request
import { usePagination } from 'vue-request'

import ProcessFlowSUBList from './ProcessFlowSUBList'
import ProcessFlowModal from './modules/ProcessFlowModal'

// Icon
const iSearch = ref('SearchOutlined')
const iReload = ref('ReloadOutlined')
const iDown = ref('DownOutlined')
const iUp = ref('UpOutlined')
const iPlus = ref('PlusOutlined')
const iEdit = ref('EditOutlined ')
const iDelete = ref('DeleteOutlined')
const iSetting = ref('SettingOutlined')

// const iUp = ref('UpOutlined')

// 时间格式转换
const formatterDate = val =>
	val ? Moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
// 子表单实例
const target = ref('')
// 表一弹窗 实例
const flowModal = ref('')

// 查询条件
const queryParam = reactive({ ord_no: '' })

// 收起 展开
const toggleSearchStatus = ref(true)

// 选中的 行
const selectedRowKeys = ref([])
// table选中 records
const selectionRows = ref([])
// 选中触发的回调
const onSelectChange = (keys, rows) => {
	selectedRowKeys.value = keys
	selectionRows.value = rows
}

// 选择框的默认属性配置 默认选中第一行
const getCheckboxProps = () => {}

// 加载中
// const loading = ref(true)

// 每一行 数据
// const dataSource = ref([])

// 动态列设置  显示--item.title  value:item.dataIndex
// const settingColumns = ref([])
// 自定义列设置 -- 气泡卡片
const defColumns = reactive([
	{
		title: '#',
		dataIndex: '',
		key: 'rowIndex',
		width: 60,
		align: 'center',
		customRender: function (t, r, index) {
			return parseInt(index) + 1
		},
	},

	{
		title: '工艺流程编码',
		align: 'center',
		dataIndex: 'ord_no',
		width: 300,
		ellipsis: true,
	},
	{
		title: '工艺流程版本',
		align: 'center',
		dataIndex: 'c01',
		width: 200,
		ellipsis: true,
	},
	{
		title: '建立用户',
		align: 'center',
		dataIndex: 'created_username',
		width: 200,
		ellipsis: true,
	},
	{
		title: '到期日期',
		align: 'center',
		dataIndex: 'due_date',
		width: 150,
		customRender: text => {
			return formatterDate(text)
		},
	},
	{
		title: '备注',
		align: 'center',
		dataIndex: 'memo',
		width: 300,
		ellipsis: true,
	},
	{
		title: '更改用户',
		align: 'center',
		dataIndex: 'updated_username',
		width: 200,
		ellipsis: true,
	},
	{
		title: '操作',
		dataIndex: 'action',
		// slots: { customRender: 'action' },
		align: 'center',
		fixed: 'right',
		width: 180,
	},
])

// 表头  默认只有  # 与 action
const defArray = defColumns.filter(
	item => item.key === 'rowIndex' || item.dataIndex === 'action'
)

const columns = ref([...defArray])

// 指定滚动区域的宽和高 number
const scrollX = ref(document.body.clientWidth - 200) // ant-header-side-opened
const scrollY = ref(document.body.clientHeight - 383) // 表格竖向滚动条,383是页面其他元素的高度

// 设置行属性
// eslint-disable-next-line no-unused-vars
const customRow = record => {
	return {
		// xxx... //属性
		onClick() {
			/**
			 * 点击行 选中 or 取消
			 * 1 没有选中  直接添加
			 * 2 有选中 是同一行   取消
			 * 3 有选中 不是同一行  选中点击的行
			 */
			if (!selectedRowKeys.value.length) {
				selectedRowKeys.value.push(record.ord_id)
			} else if (selectedRowKeys.value.includes(record.ord_id)) {
				selectedRowKeys.value = []
				return
			} else {
				selectedRowKeys.value = [record.ord_id]
			}
			// 子列表传递数据
			target.value.onSelectSubListData(record.ord_id)
		},
		// 等同 rowSelection--onChange
		onChange() {
			// 子列表传递数据
			target.value.onSelectSubListData(record.ord_id)
		},
		/*
		onDblclick: event => {},
		onContextmenu: event => {},
		onMouseenter: event => {}, // 鼠标移入行
		onMouseleave: event => {},
		*/
	}
}

// 列设置更改事件--value:item.dataIndex
// settingColumns 要做 持久化 session 取代 checkedValue
const onColSettingsChange = checkedValue => {
	// 筛选 选中的 columns
	const filterArr = defColumns.filter(item =>
		checkedValue.includes(item.dataIndex)
	)
	// 拼接 columns
	columns.value = [defArray[0], ...filterArr, defArray[1]]
}

// 初始化 table 数据
const parameter = {
	column: 'created_date',
	order: 'desc',
	field: 'ord_id',
	pageNo: 1,
	pageSize: 10,
}
// usePagination
const { data, run, loading, current, pageSize, total } = usePagination(
	p => loadOrderData(p),
	{
		defaultParams: [parameter],
		formatResult: ({ data, total }) => ({ data, total }),
		// formatResult: res => res,
		pagination: {
			currentKey: 'pageNo',
			pageSizeKey: 'pageSize',
			totalKey: 'total', // 取值 data:{ data, total } 从 { 中开始 }
		},
	}
)
// ref有数据  但是 .value 为 undefined 通过这种方式--模版使用数据
const dataSource = computed(() => data?.value?.data || [])

// 分页器
/* // 页面切换
const onPageChange = () => {}
// 页面个数切换
const onSizeChange = () => {} */
// usePagination
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value,
	pageSizeOptions: [
		'5',
		'10',
		'15',
		'20',
		'25',
		'30',
		'50',
		'100',
		'150',
		'200',
		'300',
		'500',
	],
	showTotal: (total, range) => {
		return range[0] + '-' + range[1] + ' 共' + total + '条'
	},
	showQuickJumper: true,
	showSizeChanger: true,
	serverQuery: true,
	// onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize),
	// onChange: (page, pageSize) => onPageChange(page, pageSize),
}))

// 分页、排序、筛选变化时触发 @change="handleTableChange" 参考远程加载数据
const handleTableChange = (pag, filters, sorter) =>
	run({
		pageSize: pag.pageSize,
		pageNo: pag?.current,
		sortField: sorter.field,
		sortOrder: sorter.order,
		...filters,
	})

// 表一 新增
const handleAdd = () => flowModal.value.showDrawer()
// 表一 编辑
const handleModify = () => flowModal.value.showDrawer()
</script>
<style scoped lang="less">
// 可以提到 global
.table-page-search-wrapper {
	.ant-form-inline {
		.ant-form-item {
			display: flex;
			margin-bottom: 24px;
			margin-right: 0;

			.ant-form-item-control-wrapper {
				flex: 1 1;
				display: inline-block;
				vertical-align: middle;
			}

			> .ant-form-item-label {
				line-height: 32px;
				padding-right: 8px;
				width: auto;
			}
			.ant-form-item-control {
				height: 32px;
				line-height: 32px;
			}
		}
	}

	.table-page-search-submitButtons {
		display: block;
		margin-bottom: 24px;
		white-space: nowrap;
		// ======== style="float: left; overflow: hidden"
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
}
// 新增  复制
.table-operator {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 6px 0;
}
// =================

.ant-table-tbody .ant-table-row td {
	padding-top: 5px;
	padding-bottom: 15px;
}

.anty-row-operator button {
	margin: 0 5px;
}

.ant-btn-danger {
	background-color: #ffffff;
}

.ant-modal-cust-warp {
	height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
	height: calc(100% - 110px) !important;
	overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
	height: 90% !important;
	overflow-y: hidden;
}
// 自定义 disabled
.disabled {
	color: rgba(0, 0, 0, 0.25);
	cursor: not-allowed;
}
// tabs 下面的 灰色横线
.ant-tabs {
	margin-top: 10px;
	:deep(.ant-tabs-nav):before {
		border-bottom: none;
	}
}
</style>
